import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_plugin/routes/router.dart';
import 'package:flutter_plugin/themes.dart';
import 'package:flutter_plugin/util/injection.dart';
import 'package:flutter_plugin/util/loading_util.dart';
import 'package:flutter_plugin/util/log_util.dart';
import 'package:flutter_plugin/util/sputil.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'constant/env.dart';
import 'constant/sp_key.dart';
import 'global/global_binding.dart';

void main() {
  /// 全局异常捕获
  runZonedGuarded(() async {
    FlutterError.onError = (FlutterErrorDetails errorDetails) {
      if (kDebugMode) {
        FlutterError.dumpErrorToConsole(errorDetails);
      } else {
        Zone.current.handleUncaughtError(errorDetails.exception, errorDetails.stack!);
      }
    };

    /// 初始化
    await SPUtil.init();
   /// await Injection().initDeviceId();
    LoadingUtil.configLoading();

    WidgetsFlutterBinding.ensureInitialized();
    runApp(const MyApp());
  }, (Object e, StackTrace stack) {
    logger.d('异常处理');
    logger.e(e);
    logger.e(stack);
  });
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent, statusBarBrightness: Brightness.light));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      useInheritedMediaQuery: true,
      child: GetMaterialApp(
        enableLog: Env.envConfig.debugEnable,
        defaultTransition: Transition.cupertino,
        theme: Themes.normalTheme(context),
        transitionDuration: 100.milliseconds,
        locale: const Locale('zh', 'CN'),
        getPages: AppRoutes.routes,
        initialRoute: _initRoute(),
        initialBinding: GlobalBinding(),
        builder: (context, child) =>
            FlutterEasyLoading(
              child: child,
            ),
        onInit: () {},
        onReady: () {},
      ),
    );
  }

  String _initRoute() {
    return SPUtil.instance.get(SPKey.isLogin) ?? false ? AppRoutes.home : AppRoutes.login;
  }
}
